package com.example.multilpeDataSource.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author wangzhendong
 * @data 2020-02-08 13:10
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    /**
     * 前置设置dataSource
     * @param joinPoint
     */
    @Before("@annotation(com.example.multilpeDataSource.config.RoutingDataSource)")
    public void beforeSwitchDS(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String dataSource = DataSourceContextHolder.DEFAULT_DATASOURCE;
        if (method.isAnnotationPresent(RoutingDataSource.class)){
            RoutingDataSource routingDataSource = method.getDeclaredAnnotation(RoutingDataSource.class);
            dataSource = routingDataSource.value();
        }
        DataSourceContextHolder.setDB(dataSource);
    }

    /**
     * 后置清空缓存
     * @param joinPoint
     */
    @After("@annotation(com.example.multilpeDataSource.config.RoutingDataSource)")
    public void afterSwitchDS(JoinPoint joinPoint){
        DataSourceContextHolder.clearDB();
    }

}
